from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response    # Response(ret)
from . import models, serializers
from django.db.models import F


# Create your views here.
class Goods(APIView):
    model = models.Goods
    serializer = serializers.Goods

    filter_field = 'id'         # 用来过滤的字段名

    def get(self, request: Request):
        # 有id则返回一个, 没有就返回所有->返回4个.
        ret_all = request.GET.get('ret_all')
        if ret_all:
            queryset = self.model.objects.all()
            serializer = self.serializer(queryset, many=True)
            ret = serializer.data
            return Response(ret)

        detail_id = request.GET.get(self.filter_field)

        if detail_id is None:
            page = request.GET.get('page')
            if isinstance(page, str):
                page = eval(page)

            if page is None:
                queryset = self.model.objects.all()[:4]
                serializer = self.serializer(queryset, many=True)
                ret = serializer.data
            else:
                # --- 带分页参数请求的处理
                queryset = self.model.objects.all()
                serializer = self.serializer(queryset, many=True)
                ret = serializer.data
                n = len(ret)
                if page:
                    p_nums = 6        # 每一页的商品数
                    p0, p1 = (page - 1) * p_nums, p_nums * page
                    ret = ret[p0: p1]

                    if page == 11:
                        ret = serializer.data
        else:
            model = self.model.objects.get(id=detail_id)
            serializer = self.serializer(model)
            ret = serializer.data
            # 查看商品详情时, 浏览次数+1
            model.viewed = F('viewed') + 1
            model.save()
        return Response(ret)

    def post(self, request: Request):
        # 返回指定id的商品信息
        post_data: dict = request.data
        detail_id = post_data.get('id')

        model = self.model.objects.get(id=detail_id)
        serializer = self.serializer(model)

        ret = {
            'msg': "这是post方法返回的数据!",
            'result': serializer.data,
        }

        return Response(ret)


